'''
Author: mypx
Date: 2025-10-21 15:29:19
LastEditTime: 2025-10-21 15:33:23
LastEditors: mypx mypx_coder@163.com
Description: 
'''
# 默认值模块
from typing import Dict, List
from parser.config_model import ConfigItem, DefaultValue
from parser.expression_evaluator import ExpressionEvaluator

class DefaultModule:
    """默认值模块"""
    
    def __init__(self):
        self.expression_evaluator = ExpressionEvaluator()
        self.default_values: Dict[str, List[DefaultValue]] = {}
    
    def register_default_value(self, config_item: ConfigItem) -> None:
        """注册配置项的默认值"""
        if config_item.properties.default:
            if config_item.id not in self.default_values:
                self.default_values[config_item.id] = []
            self.default_values[config_item.id].append(config_item.properties.default)
    
    def get_default_value(self, config_id: str, config_values: Dict[str, any]) -> any:
        """获取配置项的默认值"""
        defaults = self.default_values.get(config_id)
        if not defaults:
            return None
        
        # 按条件查找适用的默认值
        for default in defaults:
            if not default.condition or self.expression_evaluator.evaluate(
                default.condition.expression, config_values
            ):
                return default.value
        
        return defaults[0].value if defaults else None
    
    def apply_default_values(self, config_items: List[ConfigItem], config_values: Dict[str, any]) -> Dict[str, any]:
        """为所有配置项应用默认值"""
        updated_values = config_values.copy()
        
        for config_item in config_items:
            if config_item.id not in updated_values or updated_values[config_item.id] is None:
                default_value = self.get_default_value(config_item.id, updated_values)
                if default_value is not None:
                    updated_values[config_item.id] = default_value
                    config_item.current_value = default_value
        
        return updated_values